package com.treasure.web.interceptor.filter;

import com.treasure.web.configure.RequestReaderHttpServletRequestWrapper;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "httpServletRequestReplacedFilter", urlPatterns = "/*", asyncSupported = true)
@Order(1)
public class HttpServletRequestReplacedFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest) {
            // 获取请求中的流，将取出来的字符串，再次转换成流，然后把它放入到新request对象中。
            requestWrapper = new RequestReaderHttpServletRequestWrapper((HttpServletRequest) request);
        }

        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            // Java.io.IOException: Stream closed出现的原因是HTTP的Stream只允许操作一次，如果操作多次就会失败。
            // 该问题的解决思路是：提供一个复制流，让操作基于复制流。
            // 在chain.doFiler方法中传递新的request对象
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) {
    }
}